import { RootState } from '@/store/rootReducer';
import {
  Action,
  createSlice,
  PayloadAction,
  ThunkAction,
} from '@reduxjs/toolkit';

import * as asyncAction from './document-action';

interface CounterState {
  counter: Counter;
  his: Array<Counter>;
}

interface Counter {
  value: number;
}

const initialState: CounterState = { counter: { value: 0 }, his: [] };

const counterSlice = createSlice({
  name: 'counter',

  initialState,

  reducers: {
    asyncAdd(state) {
      state.counter.value += 4;
    },

    syncAdd(state, action: PayloadAction<{ count: number }>) {
      state.counter.value += action.payload.count;
    },

    increment(state) {
      state.counter.value += 1;
    },

    decrement(state) {
      state.his.push(state.counter);
      state.counter.value -= 1;
    },

    incrementByAmount(state, action: PayloadAction<Counter>) {
      state.counter.value += action.payload.value;
    },
  },
  extraReducers: {},
});

export type AppThunk = ThunkAction<void, RootState, unknown, Action<string>>;

export default { ...counterSlice.actions };

export const staticActions = counterSlice.actions;

export const CounterReducer = counterSlice.reducer;

export const actions = { ...asyncAction, ...counterSlice.actions };

export const fetchIssue = (): AppThunk => (dispatch) => {
  try {
    dispatch(counterSlice.actions.asyncAdd());
    setTimeout(() => {
      dispatch(counterSlice.actions.asyncAdd());
    }, 1000);
  } catch (err) {
      const set = 123;
      return set;
  }
};

// export const fetchIssue = (
//   org: string,
//   repo: string,
//   number: number
// ): AppThunk => async dispatch => {
//   try {
//     dispatch(getIssueStart())
//     const issue = await getIssue(org, repo, number)
//     dispatch(getIssueSuccess(issue))
//   } catch (err) {
//     dispatch(getIssueFailure(err.toString()))
//   }
// }
